package com.nerve.secondhandcar.service.impl;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.ko.commons.config.PropertyConfigurer;
import org.ko.commons.image.ImageUtils;
import org.ko.commons.upload.Num62;
import org.ko.commons.util.DateUtil;
import org.ko.core.dao.support.Finder;
import org.ko.core.domain.auth.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.nerve.secondhandcar.common.C;
import com.nerve.secondhandcar.common.bean.ImageResult;
import com.nerve.secondhandcar.common.util.ImageTool;
import com.nerve.secondhandcar.controller.model.PictureModel;
import com.nerve.secondhandcar.dao.PictureDao;
import com.nerve.secondhandcar.domain.Picture;
import com.nerve.secondhandcar.service.PictureService;

/**
 * 平台中的图片资源Service接口实现
 * @author 集成显卡
 * @version 2014-10-10 10:56:05
 */
@Service
@Transactional
public class PictureServiceImpl implements PictureService {

	@Autowired
	private PictureDao dao;

	@Override
	public Picture addDo(Picture bean) {
		dao.save(bean);

		return bean;
	}
	
	public void create(PictureModel model)throws Exception{
		Picture entity = (model.getBean());
		if(entity != null){
			if(entity.getId() != null && entity.getId() >0){
				dao.merge(entity);
			}else{
				dao.save(entity);
			}
		}
	}
	/**
	 * 删除实体
	 * @param model
	 * @throws Exception
	 */
	public void delete(PictureModel model, HttpServletRequest req)throws Exception{
		Picture pic = dao.get(model.getId());
		
		//服务器项目目录
		String serverPath=req.getSession().getServletContext().getRealPath("");
		
		deleteFile(serverPath+pic.getOrigin());
		deleteFile(serverPath+pic.getPath());
		deleteFile(serverPath+pic.getThumb());
		
		dao.delete(pic);
		//dao.delete(model.getId());
	}
	
	private void deleteFile(String path){
		try{
			new File(path).delete();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 刷新实体
	 * @param model
	 * @throws Exception
	 */
	public void refresh(PictureModel model)throws Exception{
		
	}
	
	/**
	 * 浏览详情
	 * @param model
	 * @throws Exception
	 */
	public void view(PictureModel model)throws Exception{
		Picture entity = dao.get(model.getId());
		Assert.notNull(entity, "你查看的对象不存在");
		
		model.setBean(entity);
	}
	
	/**
	 * 分页浏览
	 * @param model
	 * @throws Exception
	 */
	public void list(PictureModel model)throws Exception{
		StringBuilder sb = new StringBuilder("FROM Picture where 1=1");
		Finder f = Finder.create(sb.toString());
		f.append(" order by id desc");
		
		dao.find(f, model);
	}
	
	/**
	 * 判断实体是否存在
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public boolean isExist(PictureModel model)throws Exception{
		return false;
	}
	
	@Override
	public void dealUploadImage(HttpServletRequest req, MultipartFile mFile, ImageResult imgResult, Picture pic) throws Exception {
		//读取用户
		Object obj = SecurityUtils.getSubject().getPrincipal();
		Assert.notNull(obj, "请先登录");
		User user = (User)obj;
		
		Assert.notNull(mFile, "没有文件对象！");
		Assert.notNull(pic, "Picture对象不能为空");
		Assert.notNull(imgResult, "ImageResult对象不能为空");
		
		String ext = FilenameUtils.getExtension(mFile.getOriginalFilename());
		Assert.isTrue(ImageUtils.isValidImageExt(ext), "文件格式不正确，请上传图片文件:"+mFile.getOriginalFilename());
		
		String dateFormat = "yyyyMM";
		
		/*
		 * 第一步，保存原文件
		 * 
		 * 路径例子： upload/201410/xxxxxxxxxxxxxxxxxx.jpg
		 */
		String separa = "/";
		//服务器项目目录
		String serverPath=req.getSession().getServletContext().getRealPath("");
		//文件保存相对目录，以日期命名
		String fpath= PropertyConfigurer.getProperty(C.UPLOAD_DIR) + separa + DateUtil.getDate(dateFormat);
		
		String randomName = RandomStringUtils.random(30, Num62.N62_CHARS);
		
		File originFile = new File(serverPath + fpath);
		if(!originFile.exists()){
			System.out.println(originFile.getAbsolutePath()+" 这个目录不存在，现在创建！");
			originFile.mkdirs();
		}
		
		//保存原文件
		originFile = new File(originFile.getAbsolutePath(), randomName+"."+ ext);
		mFile.transferTo(originFile);
		
		String normalFileName = StringUtils.join(serverPath, fpath,separa, randomName, "_normal."+ext);
		/*
		 * 第二步：压缩图片
		 */
		ImageTool imgTool = new ImageTool();
		imgTool.resize(
				originFile.getAbsolutePath(), 
				normalFileName, 
				imgResult.getWidth(),
				imgResult.getHeight()
				);
		
		String thumbFileName = StringUtils.join(serverPath, fpath,separa, randomName, "_thumb."+ext);
		/*
		 * 第三步：生成缩略图
		 */
		if(imgResult.isCreateThumb()){
			imgTool.resize(
					normalFileName, 
					thumbFileName, 
					imgResult.getWidthThumb(),
					imgResult.getHeightThumb()
					);
		}
		
		imgResult.setPath(StringUtils.join(fpath, separa, randomName, "_normal."+ext));
		imgResult.setPathOrigin(StringUtils.join(fpath,separa, randomName, "."+ext));
		imgResult.setPathThumb(StringUtils.join(fpath,separa, randomName, "_thumb."+ext));
		
		pic.setFileName(mFile.getOriginalFilename());
		savePicture(pic, imgResult, user);
		
		//判断是否需要删除原文件
		if(imgResult.isDeleteOrigin()){
			try{
				originFile.delete();
			}catch(Exception e){}
		}
	}
	
	/**
	 * 保存Picture对象
	 * @method name: savePicture
	 * @return type: void
	 *	@param pic
	 *	@param imgResult
	 *	@param user
	 */
	private void savePicture(Picture pic, ImageResult imgResult, User user){
		pic.setPostDate(DateUtil.getDate());
		pic.setPath(imgResult.getPath());
		pic.setThumb(imgResult.getPathThumb());
		pic.setOrigin(imgResult.getPathOrigin());
		
		pic.setUserId(user.getId()+"");
		pic.setUserName(user.getName());
		
		try {
			if(pic.getAppId() > 0)
				dao.save(pic);
		} catch (Exception e) {
		}
	}

	@Override
	public void sort(PictureModel model) throws Exception {
		Picture p = dao.get(model.getId());
		Assert.notNull(p, "图片不存在");
		
		p.setSort(model.getSort());
		dao.merge(p);
	}
}